/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.storecash.web;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.common.collect.Maps;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.time.DateFormatUtil;
import com.jeeplus.modules.college.entity.College;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.storebank.entity.StoreBank;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.cashprop.entity.CashProp;
import com.jeeplus.modules.cashprop.service.CashPropService;
import com.jeeplus.modules.storebank.service.StoreBankService;
import com.jeeplus.modules.store.entity.Store;
import com.jeeplus.modules.store.service.StoreService;
import com.jeeplus.modules.storecash.entity.StoreCash;
import com.jeeplus.modules.storecash.service.StoreCashService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;

/**
 * 厂家提现Controller
 * @author lixinapp
 * @version 2019-10-14
 */
@Controller
@RequestMapping(value = "${adminPath}/storecash/storeCash")
public class StoreCashController extends BaseController {

	@Autowired
	private StoreCashService storeCashService;
	@Autowired
	private StoreService storeService;
	@Autowired
	private CashPropService cashPropService;
	@Autowired
	private StoreBankService storebankService;

	@ModelAttribute
	public StoreCash get(@RequestParam(required=false) String id) {
		StoreCash entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = storeCashService.get(id);
		}
		if (entity == null){
			entity = new StoreCash();
		}
		return entity;
	}
	
	/**
	 * 厂家提现列表页面
	 */
	@RequiresPermissions("storecash:storeCash:list")
	@RequestMapping(value = {"list", ""})
	public String list(StoreCash storeCash, Model model) {
		model.addAttribute("storeCash", storeCash);
		return "modules/storecash/storeCashList";
	}
	
		/**
	 * 厂家提现列表数据
	 */
	@ResponseBody
	@RequiresPermissions("storecash:storeCash:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(StoreCash storeCash, HttpServletRequest request, HttpServletResponse response, Model model) {
		// 判断当前登录用户
		User user = UserUtils.getUser();
		if (user.isShop()) {
			storeCash.setDataScope(" AND store.user_id = '"+user.getId()+"' ");
		}
		Page<StoreCash> page = storeCashService.findPage(new Page<StoreCash>(request, response), storeCash); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑厂家提现表单页面
	 */
	@RequiresPermissions(value={"storecash:storeCash:view","storecash:storeCash:add","storecash:storeCash:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(StoreCash storeCash, Model model) {
		String balance = "0";
		String username = "";
		String bank = "";
		String account = "";
		// 判断当前登录用户
		User user = UserUtils.getUser();
		if (user.isShop()) {
			Store store = storeService.findUniqueByProperty("user_id", user.getId());
			if (store != null) {
				balance = store.getBalance();
				List<Map<String, Object>> list = storebankService.executeSelectSql(
						"SELECT * FROM t_store_bank WHERE state = '0' AND store_id='"
								+ store.getId() + "'");
				if (list != null && !list.isEmpty()) {
					for (Map<String, Object> data : list) {
						if ("0".equals(data.get("state").toString())) {
							username = data.get("username").toString();
							bank = data.get("bank").toString();
							account = data.get("account").toString();
						}
					}
				}
			}
		}

		model.addAttribute("balance", balance);
		model.addAttribute("username", username);
		model.addAttribute("bank", bank);
		model.addAttribute("account", account);
		model.addAttribute("storeCash", storeCash);
		return "modules/storecash/storeCashForm";
	}
	/**
	 * 查看，增加，编辑厂家微信提现表单页面
	 */
	@RequiresPermissions(value={"storecash:storeCash:add"},logical=Logical.OR)
	@RequestMapping(value = "formwx")
	public String formwx(StoreCash storeCash, Model model) {
		String balance = "0";
		String Txname = "";
		// 判断当前登录用户
		User user = UserUtils.getUser();
		if (user.isShop()) {
			Store store = storeService.findUniqueByProperty("user_id", user.getId());
			if (store != null) {
				balance = store.getBalance();
			}
			Member member= store.getMember();
			if (member != null) {
				Txname = member.getTxname();
			}
		}

		model.addAttribute("txname", Txname);
		model.addAttribute("balance", balance);
		model.addAttribute("storeCash", storeCash);
		return "modules/storecash/storeCashFormwx";
	}
	/**
	 * 保存厂家提现
	 */
	@ResponseBody
	@RequiresPermissions(value={"storecash:storeCash:add","storecash:storeCash:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(StoreCash storeCash, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		if (StringUtils.isBlank(storeCash.getId())) {
			User user = UserUtils.getUser();
			if (user.isShop()) {
				Store store = storeService.findUniqueByProperty("user_id", user.getId());
				if (new BigDecimal(storeCash.getAmount()).compareTo(new BigDecimal(store.getBalance())) > 0) {
					j.setSuccess(false);
					j.setMsg("可用余额不足");
					return j;
				}
				String pay="0";
				if("1".equals(storeCash.getPay())){
					String orderId ="TX" + IdGen.getOrderNo();//提现单号
					storeCash.setOrderno(orderId);
					pay="1";
					String price =storeCash.getAmount();
					if(Double.valueOf(price) < 1.0){
						j.setSuccess(false);
						j.setMsg("微信单次提现不可小于1元");
						return j;
					}
					if(Double.valueOf(price) > 5000.0){
						j.setSuccess(false);
						j.setMsg("微信单次提现不可超过5000元");
						return j;
					}

					Member member= store.getMember();
					if (member != null) {
						if (member.getTxopenid() == null || member.getTxopenid().isEmpty()) {
							j.setSuccess(false);
							j.setMsg("未绑定提现微信,不能提现,请关注我惠云店公众号---点击左下角的商城首页---进入到我的（没有登录的需要登录）--点击右上角的齿轮--点击 商家微信提现绑定");
							return j;
						}
					}else{
						j.setSuccess(false);
						j.setMsg("此商户的云网账号获取失败。不能提现");
						return j;
					}
				}
				// 手续费
				BigDecimal prop = BigDecimal.ZERO;
				
				List<CashProp> propList = cashPropService.findList(new CashProp());
				for (CashProp cashProp : propList) {
					if ("1".equals(cashProp.getType())) {
						prop = new BigDecimal(cashProp.getProp());
						break;
					}
				}
				
				storeCash.setStore(store);
				storeCash.setState("0");
				
				/**
				 * 后台hibernate-validation插件校验
				 */
				String errMsg = beanValidator(storeCash);
				if (StringUtils.isNotBlank(errMsg)){
					j.setSuccess(false);
					j.setMsg(errMsg);
					return j;
				}

				storeCash.setPay(pay);
				storeCash.setFee(prop.multiply(new BigDecimal(storeCash.getAmount())).toString());
				storeCashService.add(storeCash);
			}
		}
		
		j.setSuccess(true);
		j.setMsg("申请提现成功");
		return j;
	}
	
	
	/**
	 * 审核厂家提现
	 */
	@ResponseBody
	@RequiresPermissions(value="storecash:storeCash:edit")
	@RequestMapping(value = "audit")
	public AjaxJson audit(StoreCash storeCash, String type) throws Exception{
		AjaxJson j = new AjaxJson();
//		if (!"0".equals(storeCash.getState())) {
//			j.setSuccess(false);
//			j.setMsg("只能操作待审核的申请");
//			return j;
//		}
		if ("3".equals(storeCash.getState())) {
			j.setSuccess(false);
			j.setMsg("不能操作已打款的申请");
			return j;
		}
		storeCash.setState(type);
		storeCash.setAuditDate(new Date());
		AjaxJson data = storeCashService.audit(storeCash);
		j.setSuccess(true);
		j.setMsg("审核厂家提现成功");
		return data;
	}
	
	/**
	 * 删除厂家提现
	 */
	@ResponseBody
	@RequiresPermissions("storecash:storeCash:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(StoreCash storeCash) {
		AjaxJson j = new AjaxJson();
		storeCashService.delete(storeCash);
		j.setMsg("删除厂家提现成功");
		return j;
	}
	
	/**
	 * 批量删除厂家提现
	 */
	@ResponseBody
	@RequiresPermissions("storecash:storeCash:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			storeCashService.delete(storeCashService.get(id));
		}
		j.setMsg("删除厂家提现成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("storecash:storeCash:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(StoreCash storeCash, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "厂家提现"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<StoreCash> page = storeCashService.findPage(new Page<StoreCash>(request, response, -1), storeCash);
			for (StoreCash StoreCash : page.getList()) {
				BigDecimal bigDecimal = new BigDecimal(storeCash.getAccount());
				String out = bigDecimal.toPlainString();
				StoreCash.setAccount(out);
			}
    		new ExportExcel("厂家提现", StoreCash.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出厂家提现记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("storecash:storeCash:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<StoreCash> list = ei.getDataList(StoreCash.class);
			for (StoreCash storeCash : list){
				try{
					storeCashService.save(storeCash);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条厂家提现记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条厂家提现记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入厂家提现失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入厂家提现数据模板
	 */
	@ResponseBody
	@RequiresPermissions("storecash:storeCash:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "厂家提现数据导入模板.xlsx";
    		List<StoreCash> list = Lists.newArrayList(); 
    		new ExportExcel("厂家提现数据", StoreCash.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }

}